// node version >= 14.14.0
const FS = require("fs");
const repl = require('repl');
const readline = require('readline');

console.log("文件重命名：.a, 退出：.exit")
let replServer = repl.start(">")
replServer.defineCommand('a', {
  help: '文件重命名',
  action() {
    rename();
  }
});

// 文件重命名
function rename() {
	const rl = readline.createInterface({
		input: process.stdin,
		output: process.stdout
	});

	rl.question(`要替换的文字：`, (target) => {
		rl.question(`替换后的文字：`, (result) => {
			let dirs = FS.readdirSync("./")
			dirs = dirs.filter(item=>item.includes(target)&&FS.statSync(item).isFile())
			dirs.forEach(file=>{
				let fileName = file.replace(target,result);
				FS.rename(file,fileName,()=>{
					console.log(file+"->"+'\x1B[32m%s\x1B[0m', fileName)
				})
				
			})
			console.log("替换了"+'\x1B[32m%s\x1B[0m',dirs.length,"个")
			rl.close();
		})
	})
}
